package com.chu.cloud.api.handler;

import com.chu.cloud.api.thread.MemberContextLocal;
import com.chu.cloud.enums.RedisKeyPrefix;
import com.chu.cloud.feign.client.IUserFeignClient;
import com.chu.cloud.response.ResponseMessage;
import com.chu.cloud.util.JsonUtils;
import com.chu.cloud.util.RedisUtil;
import com.chu.cloud.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/4/13 11:07
 * @Description: 拦截url
 */
@Slf4j
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private IUserFeignClient userFeignClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        UserVo user = RedisUtil.get(RedisKeyPrefix.TOKEN_MEMBER, token, UserVo.class);
        if (user != null) {
            RedisUtil.set(RedisKeyPrefix.TOKEN_MEMBER, token, user, 3600);
            MemberContextLocal.set(user);
            return true;
        }
        ResponseMessage<UserVo> responseMessage = userFeignClient.findByToken(token);
        if (responseMessage.getData() == null || responseMessage.getCode() != 200) {
            PrintWriter print = response.getWriter();
            ResponseEntity<String> r = new ResponseEntity<>("token失效,请登录!", HttpStatus.FORBIDDEN);
            print.write(JsonUtils.obj2json(r));
            print.close();
            print.flush();
            return false;
        }
        //放入线程隔离对象中去
        MemberContextLocal.set(responseMessage.getData());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //线程隔离对象一次请求有效
        MemberContextLocal.remove();
    }
}
